package com.wowangz.cms.dailyoperation.messageswitch.api;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.wowangz.cms.common.pojo.AjaxDataEntity;
import com.wowangz.cms.common.utils.DictTypeConstant;
import com.wowangz.cms.common.utils.SysConstant;
import com.wowangz.cms.component.datagrid.pojo.DataGrid;
import com.wowangz.cms.component.datagrid.pojo.DataResult;
import com.wowangz.cms.component.datagrid.pojo.DataStyle;
import com.wowangz.cms.component.datagrid.pojo.PangingParam;
import com.wowangz.cms.component.datagrid.utils.DataTypeConstant;
import com.wowangz.cms.component.datagrid.utils.PangingTools;
import com.wowangz.cms.dailyoperation.messageswitch.entity.MessageSwitch;
import com.wowangz.cms.dailyoperation.messageswitch.service.MessageSwitchService;
import com.wowangz.cms.dailyoperation.store.pojo.StoreEntity;
import com.wowangz.cms.syscore.IssTransactionContainer;
import com.wowangz.cms.syscore.api.BaseController;
import com.wowangz.cms.syscore.api.JSONFactory;
import com.wowangz.cms.syscore.utils.MessageResourcesUtils;
import com.wowangz.cms.syscore.utils.ServletUtils;

@Scope("prototype")
@Controller
public class MessageSwitchController extends BaseController {
	/**
	 * 进入短信开关管理页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/dailyoperation/storemessageSwitch/messageSwitchmanageList.web")
	public String toMessageSwitchmanageList(HttpServletRequest request, HttpServletResponse response, Model model) {
		return "/WEB-INF/jsp/dailyoperation/messageSwitchmanage/messageSwitchmanageList";
	}
	/**
	 * 短信开关管理 列表加载列表数据
	 * @param request
	 * @param response
	 * @param model
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/dailyoperation/storemessageSwitch/queryMessageSwitchmanageListInfoDataGrid.json")
	public void queryMessageSwitchmanageListInfoDataGrid(HttpServletRequest request, HttpServletResponse response, Model model) {
		MessageSwitchService messageSwitchService = (MessageSwitchService) IssTransactionContainer.getInstance(MessageSwitchService.class, false);
		PangingParam pangingParam = null;
		DataResult dataResult = new DataResult();
		DataGrid dataGrid = null;
		try {
			pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			HashMap<String, Object> map = (HashMap) ServletUtils.getParametersToHashMap(request);
			dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);
			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getEndrow());
			map.put("rows", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			map.put("order", dataGrid.getOrder());
			map.put("state", SysConstant.CommonApproveStatus.OK);
			map.put("statusid", SysConstant.RecordStatus.VALID);
			long resultCount = messageSwitchService.findMessageSwitchStoreForListResultCount(map);
			List<StoreEntity> resultList = messageSwitchService.findMessageSwitchStoreForListResultList(map);
			DataStyle dataStyle = new DataStyle();
			dataStyle.setPageIndex(pangingParam.getPage());
			dataStyle.setDataCount(resultCount);
			dataStyle.setDataList(resultList);
			dataStyle.addDepict("id", DataTypeConstant.STRING);
			dataStyle.addDepict("number", DataTypeConstant.STRING);
			dataStyle.addDepict("name", DataTypeConstant.STRING);
			dataStyle.addDepict("corporate", DataTypeConstant.STRING);
			dataStyle.addDepictByDataDictionary("population", DictTypeConstant.POPULATION);
			dataStyle.addDepictByDataDictionary("industry", DictTypeConstant.STOREINDUSTRY);
			dataStyle.addDepictByDataDictionary("quality", DictTypeConstant.QUALITY);
			dataResult = PangingTools.buildResultPagerInfo(dataStyle);
			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, userContext));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**********
	 * 进入 商户开关设置  明细列表页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/dailyoperation/storemessageSwitch/messageSwitchdetailmanageList.web")
	public String toMessageSwitchmanagedetailList(HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			String storeId=request.getParameter("storeid");
			MessageSwitchService messageSwitchService = (MessageSwitchService) IssTransactionContainer.getInstance(MessageSwitchService.class, false);
			Map<String, Object> map =new HashMap<String, Object>();
			map.put("storeid", storeId);
			map.put("statusid", SysConstant.RecordStatus.VALID);
			StoreEntity storeEntity=messageSwitchService.queryStoreInfo(map);
			if(storeEntity!=null && !("").equals(storeEntity)){
				saveOtherMessageSwitchInfo(storeId);
			}
			model.addAttribute("storeEntity", storeEntity);
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("storeid", request.getParameter("storeid"));
		return "/WEB-INF/jsp/dailyoperation/messageSwitchmanage/messageSwitchdetailmanageList";
	}
	/**
	 * 商户开关设置  明细页面  列表加载列表数据
	 * @param request
	 * @param response
	 * @param model
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/dailyoperation/storemessageSwitch/queryMessageSwitchDetailManageListInfoDataGrid.json")
	public void queryMessageSwitchDetailManageListInfoDataGrid(HttpServletRequest request, HttpServletResponse response, Model model) {
		MessageSwitchService messageSwitchService = (MessageSwitchService) IssTransactionContainer.getInstance(MessageSwitchService.class, false);
		PangingParam pangingParam = null;
		DataResult dataResult = new DataResult();
		DataGrid dataGrid = null;
		try {
			pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			HashMap<String, Object> map = (HashMap) ServletUtils.getParametersToHashMap(request);
			dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);
			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getEndrow());
			map.put("rows", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			map.put("order", dataGrid.getOrder());
			map.put("statusid", SysConstant.RecordStatus.VALID);
			long resultCount =messageSwitchService.findMessageSwitchForListResultCount(map);
			List<MessageSwitch> resultList = messageSwitchService.findMessageSwitchForListResultList(map);
			DataStyle dataStyle = new DataStyle();
			dataStyle.setPageIndex(pangingParam.getPage());
			dataStyle.setDataCount(resultCount);
			dataStyle.setDataList(resultList);
			dataStyle.addDepict("id", DataTypeConstant.LONG);
			dataStyle.addDepict("isswitch", DataTypeConstant.LONG);
			dataStyle.addDepictByFunction("isswitchname", SysConstant.CommonUsedStatus.class, "getName", new Class[]{long.class});
			dataStyle.addDepictByFunction("smstype", SysConstant.MessageSwitchType.class, "getName", new Class[]{long.class});
			dataResult = PangingTools.buildResultPagerInfo(dataStyle);
			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, userContext));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/********
	 * 查看 商户开关设置  明细页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/dailyoperation/storemessageSwitch/messageSwitchmanageView.web",method = { RequestMethod.GET, RequestMethod.POST })
	public String messageSwitchmanageView(HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			String storeId=request.getParameter("storeid");
			MessageSwitchService messageSwitchService = (MessageSwitchService) IssTransactionContainer.getInstance(MessageSwitchService.class, false);
			HashMap<String, Object> map = ServletUtils.getParametersToHashMap(request);
			map.put("storeid", storeId);
			map.put("statusid", SysConstant.RecordStatus.VALID);
			StoreEntity storeEntity=messageSwitchService.queryStoreInfo(map);
			if(storeEntity!=null && !("").equals(storeEntity)){
				saveOtherMessageSwitchInfo(storeId);
			}
			List<MessageSwitch> list=messageSwitchService.queryMessageSwitchForList(map);
			for (MessageSwitch messageSwitch : list) {
				messageSwitch.setSmstypename(SysConstant.MessageSwitchType.getName(messageSwitch.getSmstype()));
				messageSwitch.setIsswitchname(SysConstant.isMessageSwitch.getName(messageSwitch.getIsswitch()));
			}
			model.addAttribute("storeEntity",storeEntity);
			model.addAttribute("list",list);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/WEB-INF/jsp/dailyoperation/messageSwitchmanage/messageSwitchmanageView";
	}
	
	/**************
	 * 启停功能  主页面
	 * @param request
	 * @param response
	 * @param model
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "/dailyoperation/storemessageSwitch/batchStartInfo.json",method = { RequestMethod.GET, RequestMethod.POST })
	public void batchStartInfo(HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		try {
			MessageSwitch messageSwitch = (MessageSwitch) ServletUtils.getParametersToBaseEntity(request,MessageSwitch.class);
			MessageSwitchService messageSwitchService = (MessageSwitchService) IssTransactionContainer.getInstance(MessageSwitchService.class,true);
			if(messageSwitch.getIds()!=null && !(messageSwitch.getIds()).equals("")){
				String[] ids=messageSwitch.getIds().split(";");
				String status=request.getParameter("status");
				List list=Arrays.asList(ids);
				if(list!=null && list.size()>0){
					for (int i = 0; i < list.size(); i++) {
						String storeid=list.get(i).toString();
						saveOtherMessageSwitchInfo(storeid);
					}
				}
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("statusid",SysConstant.RecordStatus.VALID);
				map.put("storeids", list);
				List<MessageSwitch> listMessage=messageSwitchService.queryMessageSwitchForList(map);
				for (MessageSwitch messageSwitch2 : listMessage) {
					if(status!=null && StringUtils.equals(status,String.valueOf(SysConstant.CommonUsedStatus.START))){
						messageSwitch2.setIsswitch(SysConstant.CommonUsedStatus.START);
					}else{
						throw new Exception(MessageResourcesUtils.getMessage(request, "dailyoperation.storechargemanage.alert.stopandstart.start.statusexception"));
					}
					messageSwitch2.setModifytime(new Date());
					messageSwitch2.setModifyuserid(userContext.getLoginUser().getId());
					messageSwitchService.updateMessageSwitch(messageSwitch2);
				}
				userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "dailyoperation.storechargemanage.alert.stopandstart.start.success"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "dailyoperation.storechargemanage.alert.stopandstart.start.failure")+e.getMessage());
		}finally {
			try {
				response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity,userContext));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**************
	 * 启停功能 明细页面 
	 * @param request
	 * @param response
	 * @param model
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "/dailyoperation/storemessageSwitch/batchStartDetailInfo.json",method = { RequestMethod.GET, RequestMethod.POST })
	public void batchStartDetailInfo(HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		try {
			MessageSwitch messageSwitch = (MessageSwitch) ServletUtils.getParametersToBaseEntity(request,MessageSwitch.class);
			MessageSwitchService messageSwitchService = (MessageSwitchService) IssTransactionContainer.getInstance(MessageSwitchService.class,true);
			if(messageSwitch.getIds()!=null && !(messageSwitch.getIds()).equals("")){
				String[] ids=messageSwitch.getIds().split(";");
				String status=request.getParameter("status");
				List list=Arrays.asList(ids);
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("statusid",SysConstant.RecordStatus.VALID);
				map.put("ids", list);
				List<MessageSwitch> listMessage=messageSwitchService.queryMessageSwitchForList(map);
				for (MessageSwitch messageSwitch2 : listMessage) {
					if(status!=null && StringUtils.equals(status,String.valueOf(SysConstant.CommonUsedStatus.START))){
						messageSwitch2.setIsswitch(SysConstant.CommonUsedStatus.START);
					}else{
						throw new Exception(MessageResourcesUtils.getMessage(request, "dailyoperation.storechargemanage.alert.stopandstart.start.statusexception"));
					}
					messageSwitch2.setModifytime(new Date());
					messageSwitch2.setModifyuserid(userContext.getLoginUser().getId());
					messageSwitchService.updateMessageSwitch(messageSwitch2);
				}
				userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "dailyoperation.storechargemanage.alert.stopandstart.start.success"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "dailyoperation.storechargemanage.alert.stopandstart.start.failure")+e.getMessage());
		}finally {
			try {
				response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity,userContext));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**************
	 * 启停功能 主页面
	 * @param request
	 * @param response
	 * @param model
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "/dailyoperation/storemessageSwitch/batchStopInfo.json",method = { RequestMethod.GET, RequestMethod.POST })
	public void batchStopInfo(HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		try {
			MessageSwitch messageSwitch = (MessageSwitch) ServletUtils.getParametersToBaseEntity(request,MessageSwitch.class);
			MessageSwitchService messageSwitchService = (MessageSwitchService) IssTransactionContainer.getInstance(MessageSwitchService.class,true);
			if(messageSwitch.getIds()!=null && !(messageSwitch.getIds()).equals("")){
				String[] ids=messageSwitch.getIds().split(";");
				String status=request.getParameter("status");
				List list=Arrays.asList(ids);
				if(list!=null && list.size()>0){
					for (int i = 0; i < list.size(); i++) {
						String storeid=list.get(i).toString();
						saveOtherMessageSwitchInfo(storeid);
					}
				}
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("statusid",SysConstant.RecordStatus.VALID);
				map.put("storeids", list);
				List<MessageSwitch> listMessage=messageSwitchService.queryMessageSwitchForList(map);
				for (MessageSwitch messageSwitch2 : listMessage) {
					if(status!=null && StringUtils.equals(status,String.valueOf(SysConstant.CommonUsedStatus.STOP))){
						messageSwitch2.setIsswitch(SysConstant.CommonUsedStatus.STOP);
					}else{
						throw new Exception(MessageResourcesUtils.getMessage(request, "dailyoperation.storechargemanage.alert.stopandstart.stop.statusexception"));
					}
					messageSwitch2.setModifytime(new Date());
					messageSwitch2.setModifyuserid(userContext.getLoginUser().getId());
					messageSwitchService.updateMessageSwitch(messageSwitch2);
				}
				userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "dailyoperation.storechargemanage.alert.stopandstart.stop.success"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "dailyoperation.storechargemanage.alert.stopandstart.stop.failure")+e.getMessage());
		}finally {
			try {
				response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity,userContext));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	/**************
	 * 启停功能 明细页面
	 * @param request
	 * @param response
	 * @param model
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "/dailyoperation/storemessageSwitch/batchStopDetailInfo.json",method = { RequestMethod.GET, RequestMethod.POST })
	public void batchStopDetailInfo(HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		try {
			MessageSwitch messageSwitch = (MessageSwitch) ServletUtils.getParametersToBaseEntity(request,MessageSwitch.class);
			MessageSwitchService messageSwitchService = (MessageSwitchService) IssTransactionContainer.getInstance(MessageSwitchService.class,true);
			if(messageSwitch.getIds()!=null && !(messageSwitch.getIds()).equals("")){
				String[] ids=messageSwitch.getIds().split(";");
				String status=request.getParameter("status");
				List list=Arrays.asList(ids);
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("statusid",SysConstant.RecordStatus.VALID);
				map.put("ids", list);
				List<MessageSwitch> listMessage=messageSwitchService.queryMessageSwitchForList(map);
				for (MessageSwitch messageSwitch2 : listMessage) {
					if(status!=null && StringUtils.equals(status,String.valueOf(SysConstant.CommonUsedStatus.STOP))){
						messageSwitch2.setIsswitch(SysConstant.CommonUsedStatus.STOP);
					}else{
						throw new Exception(MessageResourcesUtils.getMessage(request, "dailyoperation.storechargemanage.alert.stopandstart.stop.statusexception"));
					}
					messageSwitch2.setModifytime(new Date());
					messageSwitch2.setModifyuserid(userContext.getLoginUser().getId());
					messageSwitchService.updateMessageSwitch(messageSwitch2);
				}
				userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "dailyoperation.storechargemanage.alert.stopandstart.stop.success"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "dailyoperation.storechargemanage.alert.stopandstart.stop.failure")+e.getMessage());
		}finally {
			try {
				response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity,userContext));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	/*******
	 * 主要用于 在常量中 添加了开关类型  自动 加载
	 * @param listMessage
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	private Map<Object,Object> mapToMessageSwitchList(List<MessageSwitch> listMessage)throws Exception{
		try {
			Map<Object,Object> map=new HashMap<Object,Object>();
			String messageSwitchstr=SysConstant.MessageSwitchType.getModelForCheckBox();
			JSONArray jsonArray = JSONArray.fromObject(messageSwitchstr);  
			List<MessageSwitch> list = (List<MessageSwitch>) JSONArray.toCollection(jsonArray,MessageSwitch.class);  
			for (MessageSwitch jsonMessageSwitch : list) {
				map.put(jsonMessageSwitch.getKey(),jsonMessageSwitch.getValue());
				if(listMessage!=null && !("").equals(listMessage) && listMessage.size()>0){
					for (MessageSwitch inputMessageSwitch: listMessage){
						if(inputMessageSwitch.getSmstype()==Long.valueOf(jsonMessageSwitch.getKey())){
							map.remove(jsonMessageSwitch.getKey());
						}
					}
				}else{
					map.put(jsonMessageSwitch.getKey(),jsonMessageSwitch.getValue());
				}
			}
			return map;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	} 
	/**********
	 * 保存 数据
	 * @param storeId
	 * @throws Exception
	 */
	private void saveOtherMessageSwitchInfo(String storeId)throws Exception{
		try {
			MessageSwitchService messageSwitchService = (MessageSwitchService) IssTransactionContainer.getInstance(MessageSwitchService.class, false);
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("storeid", storeId);
			map.put("statusid", SysConstant.RecordStatus.VALID);
			Long count= messageSwitchService.findMessageSwitchForListResultCount(map);
			if(count!=null && count!=0){
			}else{
				StoreEntity storeEntity=messageSwitchService.queryStoreInfo(map);
				List<MessageSwitch> list=messageSwitchService.queryMessageSwitchForList(map);
				if(storeEntity!=null && !("").equals(storeEntity)){
					Map<Object,Object> resMap=mapToMessageSwitchList(list);
					for (Map.Entry<Object,Object> entry : resMap.entrySet()) {
						MessageSwitch messageSwitch=new MessageSwitch();
						messageSwitch.setStoreid(storeEntity.getId());
						messageSwitch.setSmstype(Long.valueOf(entry.getKey().toString()));
						messageSwitch.setSmstypename(entry.getKey().toString());
						messageSwitch.setIsswitch(Long.valueOf(SysConstant.isMessageSwitch.NO));
						messageSwitch.setIsswitchname(String.valueOf(SysConstant.isMessageSwitch.NO));
						messageSwitch.setStatusid(SysConstant.RecordStatus.VALID);
						messageSwitch.setInputtime(new Date());
						messageSwitch.setInputuserid(getUserContext().getLoginUser().getId());
						messageSwitch.setModifytime(new Date());
						messageSwitch.setModifyuserid(getUserContext().getLoginUser().getId());
						messageSwitchService.insertMessageSwitch(messageSwitch);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
